﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WFT.Helpers.Scheduling;

namespace WFT
{
    /// <summary>
    /// Extension methods for the type String
    /// </summary>
    public static class StringExtensions
    {
        /// <summary>
        ///  Gets the next occurrence of this crontab Expression
        /// </summary>
        /// <param name="cronExpression">Cron tab expression</param>
        /// <returns>Return the next occurrence datetime</returns>
        public static DateTime? GetNextCronOccurrence(this string cronExpression)
        {
            return GetNextCronOccurrence(cronExpression, DateTime.Now);
        }

        /// <summary>
        /// Gets the next occurrence of this crontab Expression starting with a base time.
        /// </summary>
        /// <param name="cronExpression">Cron tab expression</param>
        /// <param name="startDate">Base time</param>
        /// <param name="throwExc">Defines if an exception is throw in case of invalid crontab expression</param>
        /// <returns>Return the next occurrence datetime</returns>
        public static DateTime? GetNextCronOccurrence(this string cronExpression, DateTime startDate, bool throwExc = true)
        {
            try
            {
                CrontabSchedule schedule = CrontabSchedule.Parse(cronExpression);
                return schedule.GetNextOccurrence(startDate);
            }
            catch (Exception)
            {
                if (throwExc)
                    throw new InvalidCastException(String.Format("Invalid cron expression : {0}", cronExpression));
                else
                    return null;
            }

        }
    }
}
